#include "PptpServer.h"

PptpServer::PptpServer(QObject *parent)
    : QObject{parent}
{
    server = new QTcpServer(this);
    connect(server, &QTcpServer::newConnection, this, &PptpServer::newClientHandler);
    server->listen(QHostAddress::AnyIPv4, PORT); // 开始监听指定端口
}

void PptpServer::newClientHandler()
{
    // qDebug() << "void PptpServer::newClientHandler()";
    QTcpSocket *tcpSocket = server->nextPendingConnection(); // 获取新的连接
    if (!tcpSocket)
        return;

    // 获取当前线程的 ID 并转换为字符串
    // quintptr threadId = reinterpret_cast<quintptr>(QThread::currentThreadId());
    // QString connectionName = QString("ThreadId_%1").arg(threadId);
    // qDebug() << "主线程为：" << connectionName;

    // ServerThread *serverThread = new ServerThread(pptpSocket);
    ServerThread *serverThread = new ServerThread(tcpSocket);

    connect(serverThread, &ServerThread::threadEnd, this, [serverThread]()
            {
                serverThread->quit();
                serverThread->wait();        // 等待线程结束
                serverThread->deleteLater(); // 清除线程资源
                // qDebug() << "serverThread->deleteLater()";
            });

    serverThread->start();
    // qDebug() << "new ServerThread start";
}
